package com.liao.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.liao.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Random;


@Component
public class SmsUtil {

    static final String accessKeyId ;
    static final String accessKeySecret ;
    static {
        InputStream inputStream = SmsUtil.class.getClassLoader().getResourceAsStream("sms.properties");
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        accessKeyId = properties.getProperty("accessKeyId");
        accessKeySecret = properties.getProperty("accessKeySecret");
    }

    @Autowired
    private CodeService codeService;

    public  void sendSms(String phoneNum , HttpSession session) throws Exception {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNum);//设置手机号
        request.putQueryParameter("SignName", "oldqiu");//设置短信签名
        request.putQueryParameter("TemplateCode", "SMS_186953933");//设置短信模板


        StringBuffer randomNumStr = new StringBuffer();
        for (int i = 0; i < 4; i++) {//产生随机验证码
            randomNumStr.append(new Random().nextInt(10));
        }
        System.out.println(randomNumStr.toString());
//        session.setAttribute("randomNum",randomNumStr);
//        将手机验证码存储mysql数据库(redis)
//        根据手机查询，如果没有就是insert(),如果有就是update
        codeService.operateCode(phoneNum,randomNumStr.toString());
        request.putQueryParameter("TemplateParam", "{\"code\":\""+randomNumStr.toString()+"\"}");//设置验证码

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
